package work.jame.blog.controller.websocket;

import com.alibaba.fastjson2.JSON;
import org.springframework.stereotype.Component;
import work.jame.blog.framework.result.WebSocketResult;
import work.jame.blog.framework.result.WebSocketResultType;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 弹幕websocket
 *
 * @author : Jame
 * @date : 2023-03-22 09:26
 **/
@Component
@ServerEndpoint(value = "/bulletScreen")
public class BulletScreenWebSocket {

    private static final ConcurrentHashMap<String, BulletScreenWebSocket> map = new ConcurrentHashMap<>();

    private Session session;


    /**
     * 更新在线人数
     */
    private void updateCurrentOnLineUserCount(){
        WebSocketResult result = new WebSocketResult(WebSocketResultType.UPDATE_CURRENT_ON_LINE_USER_COUNT, map.size());
        String resultString = JSON.toJSONString(result);
        map.forEach((k, v) -> {
            v.getSession().getAsyncRemote().sendText(resultString);
        });
    }


    @OnOpen
    public void onOpen(Session session) {
        System.out.println(session.getId());
        this.session = session;
        map.put(session.getId(), this);
        //当有用户链接上时,通知所有用户更新在线人数
        updateCurrentOnLineUserCount();
    }

    @OnClose
    public void onClose(Session session) {
        map.remove(session.getId());
        updateCurrentOnLineUserCount();
    }


    @OnMessage
    public void onMessage(String message, Session session) {
        WebSocketResult result = new WebSocketResult(WebSocketResultType.SEND_BULLET_SCREEN, message);
        String resultString = JSON.toJSONString(result);
        map.forEach((k, v) -> {
            v.getSession().getAsyncRemote().sendText(resultString);
        });
    }

    @OnError
    public void onError(Session session, Throwable error) {

    }


    /**
     * 发送给指定session消息
     *
     * @param sessionId
     * @param data
     */
    public static void sendAppointSession(String sessionId, Object data) {

    }


    /**
     * 给所有客户端发消息
     */
    public static void sendAllSession() {

    }

    public Session getSession() {
        return session;
    }


}
